package com.zbec.mdrs.service;

import com.zbec.framework.core.entity.SystemCodeTable;
import com.zbec.framework.core.service.SystemDictionaryService;
import com.zbec.framework.core.vo.LabelValue;
import com.zbec.framework.security.entity.SysOrganization;
import com.zbec.framework.security.service.SecurityService;
import com.zbec.mdrs.constants.Constants;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/21.
 */
@Component
@Transactional
public class SystemDictCacheService {


    @Autowired
    private SystemDictionaryService systemDictionaryService;

    @Autowired
    private SecurityService securityService;

    @Autowired
    private CacheManager ehcacheManager;

    private Cache dictionaryCache;

    public String findSysDictionaryCode(String typeCode, String value,int mapType) {
        String key=typeCode+"_"+value;
        String code="";
        dictionaryCache = ehcacheManager.getCache(com.zbec.framework.core.constant.Constants.CORE_CACHE_NAME);
        String cacheKey = Constants.DICTIONARY_CACHE;
        Element el=dictionaryCache.get(cacheKey);
        boolean isAddCache=true;
        Map<String,String> dictionaryMap=new HashMap<String,String>();
        if (el!= null ) {
            dictionaryMap = (Map<String, String>) el.getObjectValue();
            if(dictionaryMap.get(key)!=null){
                isAddCache=false;
            }
        }
        if(isAddCache){
            switch (mapType){
                case Constants.DICTIONARY_CODE:
                    code=systemDictionaryService.getSystemDictionaryValue(typeCode,value);
                    break;
                case Constants.DICTIONARY_DESC:
                    code=systemDictionaryService.getSystemDictionaryDesc(typeCode,value);
                    break;
                case Constants.DICTIONARY_ORG_ID:
                    SysOrganization org= securityService.getOrganizationByOrgCode(value);
                    if(org!=null){
                        code=org.getId().toString();
                    }
                    break;
                default:
                    break;
            }

            dictionaryMap.put(key,code);
            Element element = new Element(cacheKey, dictionaryMap);
            dictionaryCache.put(element);
        }else{
            code=dictionaryMap.get(key);
        }
        return code;
    }
}
